import { Router, createRouter, createWebHistory } from 'vue-router'
import useUserStore from "@/store/modules/user"
import type { RouteRecordRaw } from "vue-router"
import systemRoutes from './moudles/system'
import { getRoutes } from '@/utils/routers'


// 常量路由
let constRoutes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/Login.vue'),
        meta: {
            isDefault: true
        },
    },
    {
        path: '/',
        name: 'Index',
        component: () => import('../layout/index.vue'),
        children: [
            {
                path: '/home',
                name: 'Home',
                component: () => import('../views/Home.vue'),
                meta: {
                    isDefault: true
                },
            },
            {
                path: '/403',
                name: 'Forbidden',
                component: () => import('@/views/error/403.vue'),
                meta: {
                    isDefault: true
                },
            },
            {
                path: '/500',
                name: 'Error',
                component: () => import('@/views/error/500.vue'),
                meta: {
                    isDefault: true
                },
            },
            ...systemRoutes
        ]
    },
    {
        path: '/404',
        name: 'NotFound',
        meta: {
            title: 'Page Not Found',
            isDefault: true
        },
        component: () => import('@/views/error/404.vue')
    },
    {
        path: '/:pathMatch(.*)*',
        redirect: '/404'
    }
]




const router: Router = createRouter({
    history: createWebHistory(),
    routes: constRoutes
})

router.beforeEach((to) => {
    const userStore = useUserStore()
    if (!userStore.accessToken && to.name !== 'Login') {
        if (to.path != "/login") {
            return { name: 'Login' }
        }
    }
    if (to.meta.isDefault || to.path === '/') {
        return
    }

    let names = getRoutes(userStore.menu).map(v => { return v.path })
    if (!names.includes(to.path as string)) {
        return { name: 'NotFound' }
    }
})

// const modules = import.meta.glob('@/views/**/**.vue')

// console.log("mou", modules)
// const getRoutes = (list: any) => {
//     for (let i in list) {
//         if (list[i].children) {
//             getRoutes(list[i].children);
//         } else {
//             console.log(list[i])
//             router.addRoute('Index', {
//                 ...list[i],
//                 component: modules[`.${list[i].component}`]
//             });
//         }
//     }
//     return list;
// };

export default router
export { router } 